package com.wwl.deliveryappointmentbackend.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileUtil {

    // 将输入流保存为文件
    public static void saveFile(InputStream inputStream, String filePath) throws IOException {
        FileOutputStream outputStream = new FileOutputStream(filePath);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }

    // 判断文件是否存在
    public static boolean isFileExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    // 删除文件
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        return file.delete();
    }

    // 创建目录
    public static void createDirectory(String directoryPath) throws IOException {
        Files.createDirectories(Paths.get(directoryPath));
    }

    // 获取文件扩展名
    public static String getFileExtension(String fileName) {
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        } else {
            return "";
        }
    }
    // 判断文件夹是否存在，不存在则创建
    public static void createDirectoryIfNotExists(String directoryPath) {
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs(); // 创建多级目录
        }
    }

    // 判断文件夹是否存在
    public static boolean isDirectoryExists(String directoryPath) {
        File directory = new File(directoryPath);
        return directory.exists() && directory.isDirectory();
    }
}
